package com.example.question.bt.backtrack1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Date 2023-07-16
 * @Author Jonathan
 */
public class Code03_47 {

    public static void main(String[] args) {
        Code03_47 code = new Code03_47();
        List<List<Integer>> lists = code.permuteUnique(new int[]{1, 1, 2});
        System.out.println(lists);
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        dfs(nums, new ArrayList<>(), new boolean[nums.length], res);
        return res;
    }

    private void dfs(int[] nums, List<Integer> paths, boolean[] visited, List<List<Integer>> res) {
        if (paths.size() == nums.length) {
            res.add(new ArrayList<>(paths));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            // 剪枝
            if (visited[i]) {
                continue;
            }
            // 再次剪枝
            if (i > 0 && !visited[i - 1] && nums[i] == nums[i - 1]) {
                continue;
            }
            paths.add(nums[i]);
            visited[i] = true;
            dfs(nums, paths, visited, res);
            visited[i] = false;
            paths.remove(paths.size() - 1);
        }
    }
}
